<template>
  <div>
    <el-upload
      :class="{ disabled: disabled }"
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :http-request="httpRequest"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog title="预览图片" :visible.sync="dialogShow">
      <img style="width: 100%" :src="imgUrl" alt="" />
    </el-dialog>
    <el-progress
      style="width: 200px"
      v-if="percentageShow"
      :percentage="percentageNum"
    ></el-progress>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
// 需要实例化
const cos = new Cos({
  SecretId: 'AKID40pV3NZaQ4Xs361zf6LWY0FMOPL8msuw',
  SecretKey: '2rW4UtBHJI6e3OedVDkASbaWHnEVYNBx'
}) // 实例化的包 已经具有了上传的能力 可以上传到该账号里面的存储桶了
export default {
  name: 'ImageUpload',
  data() {
    return {
      fileList: [],
      dialogShow: false,
      imgUrl: '',
      currentUid: '',
      percentageNum: 0,
      percentageShow: false
    }
  },
  computed: {
    disabled() {
      return this.fileList.length === 1
    }
  },
  methods: {
    //
    onRemove(file, fileList) {
      this.fileList = fileList
    },
    //
    onChange(file, fileList) {
      this.fileList = fileList
    },
    //
    onPreview(file) {
      this.dialogShow = true
      this.imgUrl = file.url
    },
    // 上传成功之前的钩子
    beforeUpload(file) {
      // 1.格式校验
      const typeArr = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!typeArr.includes(file.type)) {
        this.$message.warning('格式不正确')
        return false
      }
      // 2.体积校验
      if (file.size > 1024 * 1024 * 2) {
        this.$message.warning('体积不允许超过2m')
        return false
      }

      // 返回fale 不执行上传 返回true执行上传
      this.currentUid = file.uid
      this.percentageShow = true
      return true
    },
    // 覆盖上传行为的钩子函数
    httpRequest(data) {
      console.log(data) // 要上传的文件信息
      // 传统方法：封装上传请求的方法 new FormData实例
      // 第三方存储：腾讯云方式存储文件
      cos.putObject(
        {
          Bucket: 'xiajun-1316281973', // 存储桶
          Region: 'ap-nanjing', // 地域
          Key: data.file.name, // 文件名
          Body: data.file, // 要上传的文件对象
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percentageNum = progressData.percent * 100
          }
        },
        (err, data) => {
          // data返回数据之后 应该如何处理
          console.log(err || data)
          if (err) return this.$message.warning('上传失败')
          this.fileList.map((item) => {
            if (item.uid === this.currentUid) {
              item.url = 'http://' + data.Location
              item.uploaded = true
            }
          })
          setTimeout(() => {
            this.percentageShow = false
            this.percentageNum = 0
          }, 1000)
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
